How to implement a Complete Binary Tree using recursion without comparing the value of the node?

后端 未结 5 1026
甜味超标
甜味超标 2021-01-17 06:47
public void recurInsert(BinaryTree.Node root, BinaryTree.Node newNode, int height) {
    if (newNode == null) {
        System.out.println(\"InsertNode is empty, ple         


        
5条回答
  •  粉色の甜心
    2021-01-17 07:26

    The recursive method just implicitly implements the explicit stack from the example you linked to. The C# program below shows how it's done. I assume you can convert to Java easily enough.

    Note that the TreeInsert method assumes that the root node is not null.

        public class TreeNode
        {
            public TreeNode Left;
            public TreeNode Right;
            public int Value;
        }
    
        private void DoStuff()
        {
            TreeNode Root = new TreeNode {Value = 0};
            for (var i = 1; i < 10; ++i)
            {
                TreeInsert(Root, new TreeNode {Value = i}, i);
            }
            PreOrder(Root, 0);
        }
    
        private void TreeInsert(TreeNode root, TreeNode item, int node)
        {
            int parent = (node - 1)/2;
            if (parent == 0)
            {
                if (root.Left == null)
                    root.Left = item;
                else
                    root.Right = item;
            }
            else
            {
                TreeNode child = ((parent%2) == 1) ? root.Left : root.Right;
                TreeInsert(child, item, parent);
            }
        }
    
        private void PreOrder(TreeNode root, int level)
        {
            if (root == null) return;
            Console.WriteLine("{0}{1}", new String('-', 2*level), root.Value);
            PreOrder(root.Left, level+1);
            PreOrder(root.Right, level + 1);
        }
    

提交回复
热议问题